import miniApp, {
    analyticsBase,
    authorizeParams,
    gameRecorderStartParams,
    getUserInfoParams,
    loadParams,
    loginParams, ModalParams, SHARE_VIDEO_SORT_TYPE, ShareVideoRankDetail,
    toastParams, VIBRATE_TYPE
} from "../miniApp";
import gameConfig from "../../../configs/gameConfig";
import O1HD from "../../../gameEngine";
import {dataField} from "../dataField";

export interface vivoRewardedVideoAdParam {
    // 名称	数据类型	属性	默认值	描述
    adUnitId: string;		//required	广告位 id
}

export interface OnloadCB {

    adId: string;//广告标识，用来上报曝光与点击
    title: string;//广告标题
    desc: string;//广告描述
    icon: string;//推广应用的Icon图标
    imgUrlList: any[];//广告图片
    logoUrl: string;//广告标签图片
    clickBtnTxt: string;//点击按钮文本描述
    creativeType: number;//获取广告类型，取值说明：0：混合
    interactionType: number;//获取广告点击之后的交互类型，取值说明： 1：网址类 2：应用下载类 8：快应用生态应用

}

export interface VivoVideoAd {
    // 通过 load 方法主动预加载广告内容。
    // 此外，在显示广告出现问题时也可以尝试主动 load 一次。
    // 该方法返回一个 Promise，如果广告已经自动拉取成功，调用该方法返回一个 resolved Promise；
    load: () => Promise<any>;
    // 广告创建后默认是隐藏的，可以通过该方法显示广告。 该方法返回一个 Promise 对象。当广告组件正常获取素材时，该 Promise 对象会是一个 resolved Promise。当广告组件发生错误时，会是一个 rejected Promise，参数与error事件监听器获得的参数相同。
    show: () => Promise<any>;
    //绑定 load 事件的监听器，用户在手动调用 load 方法后，广告组件会预先加载。 广告组件成功拉取广告素材时会触发load事件的监听器。
    //确保监听此事件时，开发者主动调用过 load 方法。
    onLoad: (listener: Function) => void;
    // 解除绑定 load 事件的监听器。
    offLoad: (listener: Function) => void;
    //绑定 error 事件的监听器。 广告组件拉取广告素材和其他情况下如果发生错误，会触发error事件的监听器。监听器会获得一个包含errCode和errMsg属性的对象参数。
    //     errCode 详情
    onError: (listener: (error: any) => void) => void;
    //    解除绑定 error 事件的监听器。
    offError: (listener: Function) => void;
    //    绑定 close 事件的监听器。 当用户点击了 Video 广告上的关闭按钮时，会触发close事件的监听器。监听器会获得一个包含isEnded属性的对象参数，表征用户是否完整观看了视频。
    onClose: (listener: (res: { isEnded: boolean }) => void) => void;
    //解除绑定 close 事件的监听器。
    offClose: (listener: Function) => void;

    //
    destroy();
}

const vivo: any = window['qg'];
export default class VivoApi extends miniApp {
    async commitRank(rankId: dataField.RANK_ID, score: number): Promise<boolean> {
        return Promise.resolve(false);
    }

    async showRank(rankId: dataField.RANK_ID): Promise<boolean> {
        return Promise.resolve(false);
    }

    operateGameLive(): void {
        // throw new Error("Method not implemented.");
    }

    protected m_appId: string = '105471298';
    protected m_secret: string = '2a509613dc1ab0acc07d3feae0e617b1';
    protected m_adUnitId: string = '938d34e48800444ca708eafe485ca1f6';
    protected m_nAdIdList: string[] = ["82a8e6c680ec4b8d9fb960df74fc9bbb",
        "7f285298d43241fda503cb68468945de",
        "3a678c0c80f14a129589175c7c3bee90"];

    protected m_BannerId: string = "80ff60d8c3444dd59731a584d11b1ff2";
    protected m_BannerIdList: string[] = ["275dd2fa87c34ed7ae70ad09726663e0",
        "6fc862feba2f42fbac6862da13388359",
        "80ff60d8c3444dd59731a584d11b1ff2"];
    // protected m_InsertId: string = "mm9mdb790h929g3waj";

    //录屏管理器
    private m_gameRecorderManager: any = null;
    //录屏文件保存完地址
    private m_gameRecordVideoUrl: string = null;
    //视频广告组件
    private m_videoAd: VivoVideoAd = null;

    //原生广告
    private m_nativeAd = null;
    private nowNAdId: number = 0;
    private m_nAdlist: OnloadCB;
    //banner广告
    private mowBanner: number = 0;

    getUserInfo(params: getUserInfoParams): void {
        vivo.getUserInfo(params);
    }

    showToast(params: toastParams): void {
        vivo.showToast(params);
    }

    showLoading(params: loadParams): void {
        vivo.showLoading(params);
    }

    hideLoading(): void {
        vivo.hideLoading()
    }

    /** 加载原生广告 */
    showNativeAd(successCallback: (a?: any) => void,
                 errorCallback: (error: any) => void,
                 completeCallback?: () => void) { //原生广告

        this.m_nativeAd = vivo.createNativeAd({posId: this.m_nAdIdList[this.nowNAdId]});

        this.m_nativeAd.load().then((res) => {
            console.log("原生广告加载成功..." + res);

            this.nowNAdId++;
            if (this.nowNAdId == this.m_nAdIdList.length) {
                this.nowNAdId = 0;
            }

            completeCallback && completeCallback();
        }).catch((res) => {
            console.log("原生广告加载失败..." + res);

            errorCallback(res);
            completeCallback && completeCallback();
        });

        this.m_nativeAd.onLoad((res) => {

            this.m_nAdlist = res.adList[0];
            this.m_nativeAd.reportAdShow({adId: this.m_nAdlist.adId});  //原生广告曝光上报

            successCallback(this.m_nAdlist);

            // console.log("------------  res.adList : " + res.adList);
            // // console.log("------------  res.adList.adId : " + res.adList.adId);  //错误使用方法
            // console.log("------------  res.adList[0].adId : " + res.adList[0].adId);
            // console.log("------------  res.adList[0].imgUrlList[0] : " + res.adList[0].imgUrlList[0]);
            // console.log("------------  this.m_nAdlist.imgUrlList[0] : " + this.m_nAdlist.imgUrlList[0]);

        });

    }

    /** 原生广告点击上报 */
    reportAdClickNativeAd() {
        this.m_nativeAd.reportAdClick({adId: this.m_nAdlist.adId});
    }

    preCreateUnits(): void {
        this.CheckLocalToBlockCityList();
        // this.createRewardedVideovalidAppIdAd({ adUnitId: this.m_adUnitId });
        // this.m_gameRecorderManager = vivo.getGameRecorderManager();
    }

    loadAndShowPortalAd(successCallback: () => void,
                        errorCallback: (error: any) => void,
                        completeCallback?: () => void) {
        //throw new Error("Method not implemented.");
    }

    private onShareAppMessageGetReward(successCallback: () => void,
                                       errorCallback: (error: any) => void,
                                       completeCallback: () => void, isNeedModal?: boolean) {

    }

    createMoreGameBtn()//创建 <更多游戏> 按钮
    {

    }

    showInterstitialAd(onAdClose: Function, onFailed: Function) {//展示插屏广告！！！！

    }

    protected m_Bannerad: any = null
    private bannerSuccese: boolean = true

    showBannerAD(node: cc.Node,
                 successCallback?: () => void,
                 errorCallback?: (error: any) => void,
                 onCloseCallBack?: () => void,
                 setBannerPosition?: ({screenWidth, screenHeight}) => cc.Vec2)//展示banner广告
    {

        const {screenWidth, screenHeight} = vivo.getSystemInfoSync();
        let pos: cc.Vec2 = setBannerPosition && setBannerPosition({screenWidth, screenHeight}) || cc.v2(0, 0);
        // var targetBannerAdWidth = 200;
        if (this.m_Bannerad && !this.bannerSuccese) {
            this.m_Bannerad.destroy()
            this.m_Bannerad = null
        }

        if (this.m_Bannerad) {
            this.m_Bannerad.show()
                .then(() => {
                    successCallback && successCallback();
                    console.log("---------------------Banner广告直接显示成功");
                })
                .catch((err) => {
                    errorCallback && errorCallback(err);
                    console.log("---------------------Banner广告直接显示组件出现问题", JSON.stringify(err));
                });
            return
        }

        this.bannerSuccese = true;

        if (this.m_Bannerad == null) {
            this.m_Bannerad = vivo.createBannerAd({
                posId: this.m_BannerIdList[this.mowBanner],
                adIntervals: 30,
                style: {
                    // width: targetBannerAdWidth,
                    // top: screenHeight - (targetBannerAdWidth / 16) * 9, // 根据系统约定尺寸计算出广告高度
                    left: pos.x,
                    top: pos.y,
                },
            });//创建
        }


        this.m_Bannerad.onSize(size => {
            console.log(size.width, size.height, "------------banner长宽-----------");
            // this.m_Bannerad.style.top = size.height;//screenHeight - size.height;
            // this.m_Bannerad.style.left = size.width;//(screenWidth - size.width) / 2;
            // setBannerPosition && setBannerPosition({ x: this.m_Bannerad.style.left, y: this.m_Bannerad.style.top },
            //     { width: size.width, height: size.height });
        });

        this.m_Bannerad.onLoad(() => {
            if (node == null || !node.active || !node.isValid) {
                console.log("---------------------------------------------------------");
                return
            }
            this.mowBanner++;
            if (this.mowBanner == this.m_BannerIdList.length) {
                this.mowBanner = 0;
            }
            this.bannerSuccese = false;
            this.m_Bannerad
                .show()
                .then(() => {
                    successCallback && successCallback();
                    console.log("---------------------Banner广告显示成功");

                    this.m_Bannerad.onClose(() => {
                        onCloseCallBack && onCloseCallBack();
                    });
                })
                .catch((err) => {
                    errorCallback && errorCallback(err);
                    console.log("---------------------Banner广告组件显示出现问题" + err.errCode + " :" + err.errMsg);
                });
        });

        this.m_Bannerad.onError((err) => {
            this.bannerSuccese = false;
            errorCallback && errorCallback(err);
            console.log("---------------------Banner广告加载错误,错误原因：" + err.errCode + " :" + err.errMsg);
        });

    }

    hideBanner()//隐鲹banner广告
    {
        if (null != this.m_Bannerad) {
            this.m_Bannerad.hide();
            console.log('---------------------banner广告隐藏完成');
        }

    }

    loadAndShowVideoAd(successCallback: () => void,
                       errorCallback: (error: any) => void,
                       completeCallback?: () => void,
                       reportAnalyticsExplain?: string,
                       videoIdPos: number = 0): void {// 显示广告
        if (this.m_videoAd == null) {
            this.m_videoAd = vivo.createRewardedVideoAd({adUnitId: this.m_adUnitId});
        }

        let onClose = (res) => {
            if (res && res.isEnded) {
                // 给予奖励
                successCallback();
                // O1HD.getManagers().soundMgr.setSoundEnabled(true);
            } else {
                //
                errorCallback('视频中途退出');
                // O1HD.getManagers().soundMgr.setSoundEnabled(true);
            }
            this.m_videoAd.offClose(onClose);
            completeCallback && completeCallback();
            O1HD.getManagers().soundMgr.setSoundEnabled(true);
            O1HD.getManagers().soundMgr.playMusic("BGM1");
        };

        //
        this.m_videoAd.load().then(() => { //加载视频广告完成
            O1HD.getManagers().soundMgr.setSoundEnabled(false);
            this.m_videoAd.show().then(() => { //播放视频广告完成

                this.m_videoAd.onClose(onClose);
                // O1HD.getManagers().soundMgr.setSoundEnabled(true);
                // O1HD.getManagers().soundMgr.playMusic("BGM1");

            }).catch((err) => { //播放视频广告错误

                errorCallback('视频显示错误  :' + JSON.stringify(err));
                this.m_videoAd.offClose(onClose);
                completeCallback && completeCallback();
                O1HD.getManagers().soundMgr.setSoundEnabled(true);
                O1HD.getManagers().soundMgr.playMusic("BGM1");

            })

        }).catch((err) => { //加载视频广告错误

            errorCallback('视频加载错误  :' + JSON.stringify(err));
            this.m_videoAd.offClose(onClose);
            completeCallback && completeCallback();
            O1HD.getManagers().soundMgr.setSoundEnabled(true);
            O1HD.getManagers().soundMgr.playMusic("BGM1");

        });

    }

    login(params: loginParams): void {
        vivo.login(params);
    }

    authorize(params: authorizeParams): void {
        params.success && params.success();
    }

    private m_gameRecordTimeNow: number = 0;

    gameRecordStart(params: gameRecorderStartParams, onStart?: (res) => void): void {
    }

    gameRecordStop(): boolean {
        return true;
    }

    isGameRecordOver(): boolean {
        return true;
    }

    shareGameRecordVideo(successCb?: () => void, failCb?: (e?) => void): void {
    }

    /**production    线上版
     development    测试版
     preview    预览版
     * */
    isProduction(): boolean {
        return VivoApi.isProduction();
    }

    isHaveShareVideo(): boolean {
        return true;
    }

    //判断是否合法APP-ID
    validAppId(): void {
    }

    reportAnalytics(EventKey: string, data: any): void {
        console.log("vivo 发送埋点", EventKey, JSON.stringify(data));
    }

    clearMemory(): void {

    }

    shareAppMessage(args: any): void {
    }

    protected createRewardedVideoAd(param: vivoRewardedVideoAdParam) {
        // this.m_videoAd = vivo.createRewardedVideoAd(param);
    }

    /**production    线上版
     development    测试版
     preview    预览版
     * */
    static isProduction() {
        return true;
    }

    PlayLastRecordSound(scale?: number, successCb?: () => void, errorCb?: () => void): void {
    }

    StartRecordSound(): void {
    }

    StopRecordSound(successCallback?: () => void): void {
    }

    addShortcut(): Promise<boolean> {
        return Promise.resolve(false);
    }

    drawUrlImage(url: string, overCb: (spf: cc.SpriteFrame) => void): void {
    }

    getShareVideoRank(sortType: SHARE_VIDEO_SORT_TYPE, successCb: (data: ShareVideoRankDetail[]) => void): void {
    }

    showAddFavoriteGuide(successCallback?: () => void, failCallback?: () => void, completeCallback?: () => void): void {
    }

    showVideo(videoUrl: string): void {
    }

    subscribeMessage(successCallback?: () => void, failCallback?: () => void, completeCallback?: () => void): void {
    }

    private m_localInBlockCity: boolean = false;

    private CheckLocalToBlockCityList(): void {
        O1HD.getModules().gameHttpModule.getLocalPropertyInfo((res) => {
            this.m_localInBlockCity = gameConfig.IP_BLOCK_CITY.includes(res.city);
        }, (err) => {
            console.debug("-------获取区域信息错误", err);
        });
    }

    LocalInBlockCityList(): boolean {
        return this.m_localInBlockCity;
    }

    vibrate(type: VIBRATE_TYPE): void {
    }

    showModal(params: ModalParams): void {
    }

    navigateToMiniGame(appId: string, successCallback?: () => void, failCallback?: () => void): void {
        console.error('#451102928 未实现');
    }
}


















